package org.gruposp2p.proyectokarma.gwt.client.ui.document;

import java.util.ArrayList;
import java.util.Set;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.Range;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
import com.google.gwt.view.client.SingleSelectionModel;
import org.gruposp2p.proyectokarma.gwt.client.MainEntryPoint;
import org.gruposp2p.proyectokarma.gwt.client.domain.Document;
import org.gruposp2p.proyectokarma.gwt.client.util.DateUtils;
import org.gruposp2p.proyectokarma.gwt.client.widget.DocumentTableRowPopup;

import com.allen_sauer.gwt.log.client.Log;
	
public class DocumentsTablePanel extends Composite {
    
    private static DocumentsTablePanelUiBinder uiBinder = 
    	GWT.create(DocumentsTablePanelUiBinder.class);
    
    @UiField CellTable<Document> cellTable;
    @UiField SimplePager simplePager;
    DocumentListAsyncAdapter adapter;
    private int offset = 0;
    private int cellTablePageSize = 50;
    private Document selectedDocument;
    final private DocumentTableRowPopup popup = new DocumentTableRowPopup();

    final SingleSelectionModel<Document> singleSelectionModel = 
    	new SingleSelectionModel<Document>();

    interface DocumentsTablePanelUiBinder extends UiBinder<Widget, DocumentsTablePanel> { }

    public DocumentsTablePanel() {
		initWidget(uiBinder.createAndBindUi(this));
		simplePager.setVisible(false);
        cellTable.setPageSize(cellTablePageSize);
        cellTable.addColumn(new Column<Document, String>(new TextCell()) {
            @Override
            public String getValue(Document document) {
              return document.getName();
            }
          }, MainEntryPoint.INSTANCE.constants.titleColumn());
        cellTable.addColumn(new Column<Document, String>(new TextCell()) {
            @Override
            public String getValue(Document document) {
            	return DateUtils.getSimpleStringFromDate(document.getDateCreated());
            }
          }, MainEntryPoint.INSTANCE.constants.createdColumn()); 
        cellTable.addColumn(new Column<Document, String>(new TextCell()) {
            @Override
            public String getValue(Document document) {
            	return DateUtils.getSimpleStringFromDate(document.getLastUpdated());
            }
          }, MainEntryPoint.INSTANCE.constants.changedColumn()); 
        cellTable.addColumn(new Column<Document, String>(new TextCell()) {
            @Override
            public String getValue(Document document) {
            	return document.getTruncatedContent();
            }
          }, MainEntryPoint.INSTANCE.constants.contentColumn()); 
        cellTable.addColumn(new Column<Document, String>(new TextCell()) {
            @Override
            public String getValue(Document document) {
            	return (document.isPolling())? 
            			MainEntryPoint.INSTANCE.constants.yes():MainEntryPoint.INSTANCE.constants.no();
            }
          }, MainEntryPoint.INSTANCE.constants.pollingColumn());
        adapter = new DocumentListAsyncAdapter();
        singleSelectionModel.addSelectionChangeHandler(selectionHandler);
        cellTable.setSelectionModel(singleSelectionModel);
        adapter.addDataDisplay(cellTable);
        simplePager.setRangeLimited(true);
        sinkEvents(Event.ONCLICK); 
    }
    
    protected class DocumentListAsyncAdapter extends AsyncDataProvider<Document>{
        @Override
        protected void onRangeChanged(HasData<Document> view) {
			Range newRange = view.getVisibleRange();
			//loadData(newRange.getStart(), newRange.getLength());
        }
    } 
    
    public void setDocuments (Set<Document> documents) {
    	if (documents.size() > cellTablePageSize) simplePager.setVisible(true);
    	else simplePager.setVisible(false);
    	adapter.updateRowData(0, new ArrayList<Document>(documents));
    }

	Handler selectionHandler = new SelectionChangeEvent.Handler() {
		@Override
		public void onSelectionChange(SelectionChangeEvent event) {
			selectedDocument = singleSelectionModel.getSelectedObject();
		} 
	};
	
	
    public void onBrowserEvent(Event event) {
        int xCoord = DOM.eventGetClientX(event);
        int yCoord = DOM.eventGetClientY(event);
        switch (DOM.eventGetType(event)) {
	        case Event.ONCLICK: 
	        	if (selectedDocument != null && checkClickIsOnTable(xCoord,yCoord)) {
	    			popup.setPopupPosition(xCoord, yCoord);
	    			popup.show(selectedDocument);
	        	}
	            break;
        } 
    }
    
    public boolean checkClickIsOnTable (int x, int y) {
    	if (y > cellTable.getAbsoluteTop() + cellTable.getHeaderHeight()
    			&& y < cellTable.getAbsoluteTop() + cellTable.getOffsetHeight()
    			&& x > cellTable.getAbsoluteLeft()
    			&& x < cellTable.getAbsoluteLeft() + cellTable.getOffsetWidth())
    	return true;
    	else return false;
    }
		
}